// (C) Copyright 2012 Kystar. All rights reserved.

`timescale 1ns/100ps
`default_nettype none

module mcu_tx
(
    reset_n,
    sysclk,
    clk_posedge,

    datout_valid,
    datout,

    mcu_dat_out
);

    input                           reset_n;
    input                           sysclk;
    input                           clk_posedge;

    input                           datout_valid;
    input           [7:0]           datout;

    output                          mcu_dat_out;

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    reg             [7:0]           shift_out;
    reg             [2:0]           load_dat;
    reg             [1:0]           tx_dat;
    reg                             datout_valid_reg;
    reg             [7:0]           datout_reg;

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    always @(posedge sysclk) begin
        datout_valid_reg <= datout_valid;
        datout_reg <= datout;
        end

    always @(posedge sysclk or negedge reset_n) begin
        if(~reset_n)
            load_dat <= 3'h0;
        else
            load_dat <= {load_dat[1:0],datout_valid_reg};
        end

    always @(posedge sysclk or negedge reset_n) begin
        if(~reset_n)
            tx_dat <= 2'h0;
        else
            tx_dat <= {tx_dat[0],clk_posedge};
        end

    assign mcu_dat_out = shift_out[7];
    always @(posedge sysclk or negedge reset_n) begin
        if(~reset_n)
            shift_out <= 8'h00;
        else begin
            if(load_dat[2])
                shift_out <= datout_reg;
            //else if(clk_posedge)
            else if(tx_dat[1])
                shift_out <= {shift_out[6:0],1'b0};
            end
        end

endmodule
`default_nettype wire
